package kr.hkit.androidcomplete02.ch16;

import kr.hkit.androidcomplete02.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class DlgQuestenEx extends Activity implements QuestionDialgFragment.NoticeDialogListener{
	TextView tv;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch16_dialog);
		
		tv = (TextView) findViewById(R.id.ch16_dialog_tv);
	
	}
	public void mOnClick(View v){
		QuestionDialgFragment QFrg = new QuestionDialgFragment();
		Bundle bundle = new Bundle();
		bundle.putString("title", "질문");
		bundle.putString("msg", "어떤 연산 하겠습니까?");
		bundle.putString("Question1", "덧셈");
		bundle.putString("Question2", "곱셈");
		bundle.putInt("a", 3);
		bundle.putInt("b", 4);
		
		QFrg.setArguments(bundle);
		QFrg.show(getFragmentManager(), "Dialog");
	}
	@Override
	public void onDialogClick(DialogFragment dialog, int res) {
		// TODO Auto-generated method stub
		tv.setText("결과값 : " +res);
	}
}

class QuestionDialgFragment extends DialogFragment{
	NoticeDialogListener mListener;
	Bundle bundle;
	
	//Fragment 에서 Activity에게 값 전달 기법
	public interface NoticeDialogListener{
		public void onDialogClick(DialogFragment dialog, int res);
	}
	
	@Override
	public void onAttach(Activity activity) {
		Log.d("DlgQuestenEx", "QuestionDialgFragment - onAttach()");
		super.onAttach(activity);
		try{
			mListener = (NoticeDialogListener) activity;
		}catch(ClassCastException e){
			throw new ClassCastException(activity.toString() + " NoticeDialogListener 를 반드시 구현");
		}
	}
	
	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		bundle = getArguments();
		return new AlertDialog.Builder(getActivity())
				.setTitle(bundle.getString("title"))
				.setIcon(R.drawable.gang3)
				.setMessage(bundle.getString("msg"))
				.setPositiveButton(bundle.getString("Question1"), listener)
				.setNegativeButton(bundle.getString("Question2"), listener)
				.create();
	}
	
	OnClickListener listener = new OnClickListener() {		
		@Override
		public void onClick(DialogInterface dialog, int which) {
			int a = bundle.getInt("a");
			int b = bundle.getInt("b");
			switch(which){
			case DialogInterface.BUTTON_POSITIVE:
				mListener.onDialogClick(QuestionDialgFragment.this, a+b);
				break;
			case DialogInterface.BUTTON_NEGATIVE:
				mListener.onDialogClick(QuestionDialgFragment.this, a*b);
				break;
			}
			
		}
	};
}